import apiConfig from "../../utils/api.js";
Page({
  data: {
    imgBaseUrl: "",
    activeTab: "photo", // 默认显示老照片
    speechText: "哎，刚整理相机时翻到些老照片，要不要一起看看？说不定能想起咱们以前某段有意思的事呢～",
    
    // 视频配置
    currentVideoSrc: "",
    videoConfig: {
      story: "History-bg.mp4", // 老故事视频
      photo: "Photo-bg.mp4", // 老照片视频  
      book: "Book-bg.mp4"    // 书籍视频
    },
    
    // 展示相关
    displayTitle: "精选老照片",
    displayStoryList: [],
    displayPhotoList: [],
    displayBookList: [],
    
    // 播放器状态（故事朗读）
    storyAudioLoading: false,
    
    // 老故事数据
    storyList: [
      { id: 0, title: "" },
    ],
    
    // 老照片数据
    photoList: [
      { id: 1, url: "oldPic-agriculture.png" },
      { id: 2, url: "oldPic-building1.png" },
      { id: 3, url: "oldPic-building2.png" },
      { id: 4, url: "oldPic-building3.png" },
      { id: 5, url: "oldPic-guide.png" },
      { id: 6, url: "oldPic-industy.png" },
      { id: 7, url: "oldPic-lab.png" },
      { id: 8, url: "oldPic-military.png" },
      { id: 9, url: "oldPic-planToBuild.png" },
      { id: 10, url: "oldPic-view.png" },
      { id: 11, url: "oldPic-viewGroupPhoto.png" },
      { id: 12, url: "oldPic-agriculture.png" },
      { id: 13, url: "oldPic-building1.png" },
      { id: 14, url: "oldPic-building2.png" },
      { id: 15, url: "oldPic-building3.png" }
    ],
    
    // 书籍数据
    bookList: [
      { id: 1, title: "校史", cover: "book-cover1.png" },
      { id: 2, title: "名人传记", cover: "book-cover2.png" },
      { id: 3, title: "学术论文集", cover: "book-cover1.png" },
      { id: 4, title: "校园文化", cover: "book-cover2.png" },
      { id: 5, title: "教学成果", cover: "book-cover1.png" },
      { id: 6, title: "校友风采", cover: "book-cover2.png" },
      { id: 7, title: "科研成果", cover: "book-cover1.png" },
      { id: 8, title: "校园建设", cover: "book-cover2.png" },
      { id: 9, title: "教育理念", cover: "book-cover1.png" },
      { id: 10, title: "发展规划", cover: "book-cover2.png" }
    ],

    // 新增：模态数据
    storyModal: {
      show: false,
      index: 0,
      data: { id: null, title: '', content: '', audio: '' },
      isPlaying: false
    },
    photoModal: {
      show: false,
      index: 0,
      data: { id: null, url: '', caption: '', time: '' },
      slideshow: false
    },
    bookModal: {
      show: false,
      index: 0,
      data: { id: null, title: '', cover: '', author: '', desc: '' }
    }
  },
    // 新增：从后端请求故事列表，失败时回退到样例数据
    fetchStories() {
      const apiUrl = api.endpoints.STORY_LIST;
      const sampleData = {
        code: 200,
        data: [
          {
            id: 0,
            title: "",
            content: "",
            createTime: ""
          }
        ]
      };
  
      wx.request({
        url: apiUrl,
        method: 'GET',
        success: (res) => {
          if (res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
            console.log(res.data.data)
            this.setData({ storyList: res.data.data });
            this.setData({
              displayStoryList: this.data.storyList.slice(0, 3).map(item => ({
                ...item,
                desc: '点击查看完整故事内容'
              }))
            });
          } else {
            console.warn('fetchStories: API 返回异常，使用本地样例数据');
            this.setData({ storyList: sampleData.data });
          }
        },
        fail: () => {
          console.warn('fetchStories: 请求失败，使用本地样例数据');
          this.setData({ storyList: sampleData.data });
        }
      });

    },
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    let speechText = "";
    let displayTitle = "";
    let currentVideoSrc = "";
    
    // 根据tab切换气泡内容、标题和视频
    switch(tab) {
      case "story":
        speechText = "你需要了解些什么故事呢？这里有校园变迁史、重大历史事件等故事。";
        displayTitle = "精选故事集";
        currentVideoSrc = this.data.videoBaseUrl + this.data.videoConfig.story;
        break;
      case "photo":
        speechText = "哎，刚整理相机时翻到些老照片，要不要一起看看？说不定能想起咱们以前某段有意思的事呢～";
        displayTitle = "精选老照片";
        currentVideoSrc = this.data.videoBaseUrl + this.data.videoConfig.photo;
        break;
      case "book":
        speechText = "家国情怀、使命担当、开拓奋进。来，一起翻开书，看先辈们在黄坡岭写下的奋斗传奇！";
        displayTitle = "精选书籍";
        currentVideoSrc = this.data.videoBaseUrl + this.data.videoConfig.book;
        break;
    }
    
    this.setData({
      activeTab: tab,
      speechText: speechText,
      displayTitle: displayTitle,
      currentVideoSrc: currentVideoSrc
    });
    
    // 播放新视频
    this.playVideo();
  },

  // 选择列表项
  selectItem(e) {
    const id = e.currentTarget.dataset.id;
    const tab = this.data.activeTab;

    if (tab === 'story') {
      const idx = this.data.storyList.findIndex(it => it.id === id);
      this.openStoryModal(idx);
      return;
    }
    if (tab === 'photo') {
      const idx = this.data.photoList.findIndex(it => it.id === id);
      this.openPhotoModal(idx);
      return;
    }
    if (tab === 'book') {
      const idx = this.data.bookList.findIndex(it => it.id === id);
      this.openBookModal(idx);
      return;
    }
  },

  // 故事模态控制
  openStoryModal(index) {
    const item = this.data.storyList[index] || {};
    // 停止任何图片轮播，避免冲突
    if (this._photoTimer) {
      clearInterval(this._photoTimer);
      this._photoTimer = null;
      this.setData({ 'photoModal.slideshow': false });
    }

    // 先显示骨架面板
    this.setData({
      'storyModal.show': true,
      'storyModal.index': index,
      'storyModal.data.title': item.title || '加载中...',
      'storyModal.data.content': '正在加载故事内容...',
      'storyModal.isPlaying': false
    });

    // 异步尝试拉取详情 API（示例接口），失败回退本地样例
    
    const storyID = apiConfig.endpoints.STORY_ID;
    const apiUrl = `${storyID}${item.id || ''}`;
    wx.request({
      url: apiUrl,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.code === 200 && res.data.data) {
          const d = res.data.data;
          this.setData({
            'storyModal.data': {
              id: d.id,
              title: d.title,
              content: d.content,
              audio: d.audio || ''
            }
          });
          // 如果有音频，准备 inner audio
          if (d.audio) {
            this._prepareStoryAudio(d.audio);
          }
        } else {
          // 回退：使用本地 content（若没有，可显示提示）
          this.setData({
            'storyModal.data.content': item.detail || '暂无详细内容。'
          });
        }
      },
      fail: () => {
        this.setData({
          'storyModal.data.content': item.detail || '暂无详细内容（网络异常）。'
        });
      }
    });
  },

  // 使用 InnerAudioContext 创建/准备音频
  _prepareStoryAudio(src) {
    try {
      if (!this._storyAudio) {
        this._storyAudio = wx.createInnerAudioContext();
        this._storyAudio.autoplay = false;
        this._storyAudio.loop = false;
        this._storyAudio.onPlay(() => { this.setData({ 'storyModal.isPlaying': true, storyAudioLoading: false }); });
        this._storyAudio.onPause(() => { this.setData({ 'storyModal.isPlaying': false }); });
        this._storyAudio.onEnded(() => { this.setData({ 'storyModal.isPlaying': false }); });
        this._storyAudio.onWaiting && this._storyAudio.onWaiting(() => { this.setData({ storyAudioLoading: true }); });
        this._storyAudio.onCanplay && this._storyAudio.onCanplay(() => { this.setData({ storyAudioLoading: false }); });
        this._storyAudio.onError((err) => {
          console.error('storyAudio error', err);
          this.setData({ 'storyModal.isPlaying': false, storyAudioLoading: false });
          wx.showToast({ title: '音频播放出错', icon: 'none' });
        });
      }
      this._storyAudio.src = src || '';
    } catch (e) {
      console.error('prepareStoryAudio error', e);
    }
  },

  // 根据配置构建获取真实 MP3 直链的接口地址
  _getApiBase() {
    return api.ENV.API_BASE;
  },
  _getMp3Endpoint(id) {
    return `${this._getApiBase()}api/story/${id}/mp3`;
  },
  _fetchMp3RealUrl(id) {
    return new Promise((resolve, reject) => {
      if (id === undefined || id === null) { reject(new Error('INVALID_ID')); return; }
      wx.request({
        url: this._getMp3Endpoint(id),
        method: 'GET',
        success: (res) => {
          const url = res && res.data && res.data.code === 200 && Array.isArray(res.data.data) && res.data.data[0]
            ? res.data.data[0]
            : '';
          if (url) resolve(url); else reject(new Error('EMPTY_URL'));
        },
        fail: (err) => reject(err)
      });
    });
  },

  // 切换故事朗读：首次点击会去后端拿直链并缓存到 storyModal.data.audio
  toggleStoryAudio() {
    const id = this.data.storyModal && this.data.storyModal.data ? this.data.storyModal.data.id : null;
    let audioSrc = this.data.storyModal.data && this.data.storyModal.data.audio;

    // 若正在播放，点击则暂停
    if (this.data.storyModal.isPlaying) {
      try { this._storyAudio && this._storyAudio.pause(); } catch(e){}
      this.setData({ 'storyModal.isPlaying': false });
      return;
    }

    // 未播放：若已有缓存直链则直接播放
    if (audioSrc) {
      if (!this._storyAudio) this._prepareStoryAudio(audioSrc);
      try {
        this.setData({ storyAudioLoading: true });
        this._storyAudio.play();
      } catch(e) {
        this.setData({ storyAudioLoading: false });
        wx.showToast({ title: '音频启动失败', icon: 'none' });
      }
      return;
    }

    // 无缓存：点击时发起请求获取真实直链
    if (id === undefined || id === null) {
      wx.showToast({ title: '缺少音频资源', icon: 'none' });
      return;
    }
    this.setData({ storyAudioLoading: true });
    this._fetchMp3RealUrl(id)
      .then((realUrl) => {
        this.setData({ 'storyModal.data.audio': realUrl });
        // 准备并播放
        if (!this._storyAudio) this._prepareStoryAudio(realUrl);
        else this._prepareStoryAudio(realUrl);
        try {
          this._storyAudio.play();
        } catch(e) {
          this.setData({ storyAudioLoading: false });
          wx.showToast({ title: '音频启动失败', icon: 'none' });
        }
      })
      .catch((err) => {
        console.error('fetch mp3 url error', err);
        this.setData({ storyAudioLoading: false });
        wx.showToast({ title: '获取音频链接失败', icon: 'none' });
      });
  },

  closeStoryModal() {
    // 停止并销毁 InnerAudioContext（如在播放）
    try {
      if (this._storyAudio) {
        try { this._storyAudio.stop(); } catch(e){}
        this._storyAudio.offPlay && this._storyAudio.offPlay();
        this._storyAudio.offPause && this._storyAudio.offPause();
        this._storyAudio.offEnded && this._storyAudio.offEnded();
        this._storyAudio.offError && this._storyAudio.offError();
        try { this._storyAudio.destroy(); } catch(e){}
        this._storyAudio = null;
      }
    } catch (e) {
      console.warn('closeStoryModal audio cleanup error', e);
    }

    this.setData({
      'storyModal.show': false,
      'storyModal.isPlaying': false
    });
  },
  nextStory() {
    const next = (this.data.storyModal.index + 1) % this.data.storyList.length;
    this.openStoryModal(next);
  },
  prevStory() {
    const prev = (this.data.storyModal.index - 1 + this.data.storyList.length) % this.data.storyList.length;
    this.openStoryModal(prev);
  },

  // 图片模态控制
  openPhotoModal(index) {
    const item = this.data.photoList[index] || {};
    this.setData({
      'photoModal.show': true,
      'photoModal.index': index,
      'photoModal.data': {
        id: item.id,
        url: this.data.imgBaseUrl + (item.url || ''),
        caption: item.caption || '',
        time: item.time || ''
      },
      'photoModal.slideshow': false
    });
  },
  closePhotoModal() {
    this.setData({ 'photoModal.show': false, 'photoModal.slideshow': false });
  },
  nextPhoto() {
    const next = (this.data.photoModal.index + 1) % this.data.photoList.length;
    this.openPhotoModal(next);
  },
  prevPhoto() {
    const prev = (this.data.photoModal.index - 1 + this.data.photoList.length) % this.data.photoList.length;
    this.openPhotoModal(prev);
  },
  toggleSlideshow() {
    const s = !this.data.photoModal.slideshow;
    this.setData({ 'photoModal.slideshow': s });
    if (s) {
      // 自动轮播：简单实现
      this._photoTimer = setInterval(() => {
        this.nextPhoto();
      }, 2500);
    } else {
      if (this._photoTimer) { clearInterval(this._photoTimer); this._photoTimer = null; }
    }
  },

  // 书籍模态控制
  openBookModal(index) {
    const item = this.data.bookList[index] || {};
    this.setData({
      'bookModal.show': true,
      'bookModal.index': index,
      'bookModal.data': {
        id: item.id,
        title: item.title,
        cover: item.cover,
        author: item.author || '',
        desc: item.desc || '暂无简介'
      }
    });
  },
  closeBookModal() {
    this.setData({ 'bookModal.show': false });
  },
  openBookReader() {
    // 示例：跳转到阅读器页面（若无则提示）
    const book = this.data.bookModal.data;
    if (!book || !book.id) {
      wx.showToast({ title: '无可用书籍', icon: 'none' });
      return;
    }
    // 假设有 pages/bookreader/bookreader 页面
    wx.navigateTo({ url: `/pages/bookreader/bookreader?id=${book.id}` });
  },
  downloadBook() {
    wx.showToast({ title: '开始下载（示例）', icon: 'none' });
    // 实际实现略
  },

  onLoad() {
      const imgBaseUrl=api.ENV.imgBaseUrl;
      const videoBaseUrl=api.ENV.videoBaseUrl;
      this.setData({
        imgBaseUrl,
        videoBaseUrl
      });
      // 初始化展示数据
      this.initDisplayData();
      // 设置默认视频
      this.setData({
        currentVideoSrc: videoBaseUrl + this.data.videoConfig.photo
      });
    const userinfo = wx.getStorageSync('userInfo');
    if(userinfo===null){
      wx.navigateTo({
      url: '/pages/welcome/welcome',
    })
  }
  },

  onReady() {
    // 页面加载完成后播放视频
    this.playVideo();
  },

  // 播放视频
  playVideo() {
    this.videoContext = wx.createVideoContext('bgVideo', this);
    if (this.videoContext) {
      try {
        this.videoContext.play();
      } catch (e) {
        console.warn('视频播放失败:', e);
      }
    }
  },

  // 视频播放结束
  onVideoEnded() {
    console.log('视频播放结束');
    // 视频只播放一次，播放结束后不重复播放
  },

  // 初始化展示数据
  initDisplayData() {
    // 初始化老故事展示数据（只显示前3个）
    this.fetchStories();

    
    // 初始化老照片展示数据（只显示前3个）
    this.setData({
      displayPhotoList: this.data.photoList.slice(0, 3).map(item => ({
        ...item,
        title: '珍贵老照片',
        desc: '点击查看高清大图'
      }))
    });
    
    // 初始化书籍展示数据（只显示前3个）
    this.setData({
      displayBookList: this.data.bookList.slice(0, 3).map(item => ({
        ...item,
        author: item.author || '作者未知'
      }))
    });
  },

  // 查看更多内容
  showMoreContent() {
    const tab = this.data.activeTab;
    let url = '';
    
    switch(tab) {
      case 'story':
        url = '/pages/storylist/storylist';
        break;
      case 'photo':
        url = '/pages/photolist/photolist';
        break;
      case 'book':
        url = '/pages/booklist/booklist';
        break;
    }
    
    if (url) {
      wx.navigateTo({ url: url });
    } else {
      wx.showToast({ title: '功能开发中', icon: 'none' });
    }
  }
});
